package digital.store.springmvc.controller;


import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import digital.store.springmvc.service.CategoryService;
import digital.store.springmvc.service.ProductService;
import digital.store.springmvc.service.UserService;
import digital.store.tutorial.springmvc.model.Category;
import digital.store.tutorial.springmvc.model.Product;
import digital.store.tutorial.springmvc.model.User;

@Controller
@RequestMapping(value = "/login")
public class LoginController {
	@Autowired
    private UserService userService;
	
	@Autowired
    private ProductService productService;
	
	@Autowired
	private CategoryService categoryService;
	
	@RequestMapping(value="login", method = RequestMethod.POST)
	public String accessLoginForm(HttpServletRequest request,HttpSession session,Model model)
	{
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		User user = userService.checkUser(username, password);
		
		if (user.getRole().getId() == 1) 
		{
			session.setAttribute("user", user);
			return "/admin";
		}
		else 
			if (user.getRole().getId() == 2)
			{
				Collection<Product> products = productService.findAll();
				Collection<Category> categories = categoryService.findAll();
			    model.addAttribute("productsList", products);
			    model.addAttribute("categoriesSidebar", categories);
				session.setAttribute("user", user);
				return "/home";
			}
		
		return "redirect:/login/";
	}
	@RequestMapping(method = RequestMethod.GET)
	public String loginForm()
	{
		return "/login";
	}
}
